#include <windows.h>
#include <stdio.h>
#include "stdlib.h"
#define WIN32_LEAN_AND_MEAN
// This hooks vld into this app
#include "..\..\include\vld.h"

void TestAllocationMismatch_malloc_delete()
{
	int* pint = (int*)malloc(56);
	// use the wrong function to deallocate
	delete pint;
}

void TestAllocationMismatch_malloc_deleteVec()
{
	int* pint = (int*)malloc(56);
	// use the wrong function to deallocate
	delete [] pint;
}

void TestAllocationMismatch_new_free()
{
	int* pint = new int(45); // scalar new
	// use the wrong function to deallocate
	free(pint);
}

void TestAllocationMismatch_newVec_free()
{
	int* pint = new int[3]; // vector new
	// use the wrong function to deallocate
	free(pint);
}

void TestHeapMismatch()
{
	HANDLE test_heap = HeapCreate(HEAP_GENERATE_EXCEPTIONS | HEAP_CREATE_ENABLE_EXECUTE, 
		0, // initialize reserved size;
		0); // maximum size can grow
	HANDLE default_heap = GetProcessHeap();
	// Have to initialize vld with something, so it doesn't dismiss
	// the default heap as having no memory allocs in it.
	void* aptr = HeapAlloc(default_heap, 0, 42);
	// Allocate it in the new heap
	void* vptr = HeapAlloc(test_heap, 0, 56);
	// Free this using the WRONG heap!
	HeapFree( default_heap, 0, vptr);

	HeapDestroy(test_heap);
}


int main(int argc, char* argv[])
{
	printf("======================================\n");
	printf("==    MismatchTest\n");
	printf("======================================\n");

	bool bTestHeapMismatch = false;

	char szAnswer[1024] = "";
	UINT vld_options = VLDGetOptions();
	vld_options |= VLD_OPT_VALIDATE_HEAPFREE;
	VLDSetOptions(vld_options, 15, 25);

	TestAllocationMismatch_malloc_delete();
	TestAllocationMismatch_malloc_deleteVec();
	TestAllocationMismatch_new_free();
	TestAllocationMismatch_newVec_free();

	printf("\nDo you want to test heap mismatch (y/n)?\n");
	printf("Your choice >  ");
#if _MSC_VER>=1400
	gets_s(szAnswer, 1024);  
#else
	gets(szAnswer);  
#endif
	if(strcmp(szAnswer, "y")==0 || 
		strcmp(szAnswer, "Y")==0)
		bTestHeapMismatch = true;
	if (bTestHeapMismatch)
		TestHeapMismatch();

	return 0;
}